package com.neu.jpcap.test;

import jpcap.PacketReceiver;
import jpcap.packet.ARPPacket;
import jpcap.packet.EthernetPacket;
import jpcap.packet.ICMPPacket;
import jpcap.packet.IPPacket;
import jpcap.packet.Packet;
import jpcap.packet.TCPPacket;
import jpcap.packet.UDPPacket;

public class PackageReceiver implements PacketReceiver {

	@Override
	public void receivePacket(Packet packet) {
		System.out.println("接收到数据包：");
		// IP数据报
		if (packet instanceof IPPacket) {
			IPPacket ppacket = (IPPacket) packet;
			System.out.println("源IP：" + ppacket.src_ip + "  目的IP：" + ppacket.dst_ip);
			System.out.println("TTL:" + ppacket.hop_limit + " 上层协议：" + ppacket.protocol);
		}
		// ARP数据报
		if (packet instanceof ARPPacket) {
			ARPPacket arpPacket = (ARPPacket) packet;
			System.out.println("\n" + arpPacket + "\n");
		}
		// ICMP数据报
		if (packet instanceof ICMPPacket) {
			ICMPPacket icmpPacket = (ICMPPacket) packet;
			System.out.println(icmpPacket);
		}
		// TCP数据报
		if (packet instanceof TCPPacket) {
			TCPPacket tcpPacket = (TCPPacket) packet;
			EthernetPacket ethernetPacket = (EthernetPacket) packet.datalink;
			System.out.print("源IP：" + tcpPacket.src_ip + "  目的IP：" + tcpPacket.dst_ip + "发送端口：" + tcpPacket.src_port
					+ " 接收端口：" + tcpPacket.dst_port + "\n");
			System.out.print("源MAC：" + ethernetPacket.getSourceAddress() + " 目的MAC："
					+ ethernetPacket.getDestinationAddress() + "\n");
			System.out.print("协议：" + tcpPacket.protocol + "\n");
			System.out.print("数据：\n");
			for (int i = 0; i < tcpPacket.data.length; i++)
				System.out.print((char) tcpPacket.data[i]);
		}
		// UDP数据报
		if (packet instanceof UDPPacket) {
			UDPPacket udpPacket = (UDPPacket) packet;
			EthernetPacket ethernetPacket = (EthernetPacket) packet.datalink;
			System.out.print("\n源IP：" + udpPacket.src_ip + "  目的IP：" + udpPacket.dst_ip + " 源端口：" + udpPacket.src_port
					+ " 目的端口：" + udpPacket.dst_port + "\n");
			System.out.print("源MAC：" + ethernetPacket.getSourceAddress() + "  目的MAC"
					+ ethernetPacket.getDestinationAddress() + "\n");
			System.out.print("协议类型：" + udpPacket.protocol + "\n");
			System.out.print("数据");
			for (int i = 0; i < udpPacket.data.length; i++)
				System.out.print(udpPacket.data[i]);
		}
	}

}
